/*蓝牙外设单步测试页面
* 对每一步蓝牙操作进行单独控制 便于发现问题出现的环节
* 同时本页面蓝牙Api全部采用BLEAPI 可作为小程序蓝牙代码学习页面
*
* 本页暂未对每一步中对异常作出提示 仅仅在正确时更新文字说明
*/
const BLEAPI = require('../bleapi/bleapi')
const RFBMBG22A1_service_id = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
const RFBMBG22A1_characteristic_id_write = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E"
const RFBMBG22A1_characteristic_id_read = "6E400003-B5A3-F393-E0A9-E50E24DCCA9E"
const RFBMBG22A1_characteristic_id_at = "6E400004-B5A3-F393-E0A9-E50E24DCCA9E"
//devices 搜索到到蓝牙外设列表
//数据格式是:[{deviceId: "84:FD:27:EE:24:50", name: "LC0584FD27EE2450", RSSI: -55, connectable: true,...]
const test =[
  { name: '84FD27EE2450', deviceId: '84:FD:27:EE:24:50' },
  { name: '84FD27EE2456', deviceId: '84:FD:27:EE:24:56', checked: 'true' },
]
Page({

  data: {
      bleStatusLabel:"手机蓝牙状态信息",
      hwStatusLabel:"外设蓝牙状态信息",
      devices: []
  },
  radioChange: function (e) {
    console.log('当前选择蓝牙外设mac为：', e.detail.value)
    this._deviceId = e.detail.value
},
  //初始化蓝牙模块 默认主机模式
  bleOpenAdapterBtn(){
    if(this._bleAble == false){
      BLEAPI.bleOpenAdapter("central").then(()=>{
        this._bleAble = true
        this.setData({
          bleStatusLabel : "开启蓝牙成功"
        })     
    }).catch(()=>{
      this.setData({
        bleStatusLabel :"开启蓝牙失败"
      })  
    })
    }
    
  },
  //关闭蓝牙模块
  bleCloseAdapterBtn(){
    if(this._bleAble == true){
      BLEAPI.bleCloseAdapter().then(()=>{
        this._bleAble = true
        this.setData({
          bleStatusLabel : "关闭蓝牙"
        })  
    })
    }
   
  },
  //开始搜寻附近的蓝牙外围设备
  bleStartSearchBtn(){
    var serviceId =  this._serviceID
    BLEAPI.bleStartSearch(serviceId,true).then(()=>{
      this.setData({
        bleStatusLabel : "开启蓝牙搜索成功"
      })     
    })
    
  },
//停止搜寻附近的蓝牙外围设备
  bleStopSearchBtn(){
    BLEAPI.bleStopSearch.then(()=>{
      this.setData({
        bleStatusLabel : "关闭蓝牙搜索成功"
      })     
    })
  },
//监听搜索到新设备的事件
  bleOnDeviceFoundBtn(){
    BLEAPI.bleOnDeviceFound((devices)=>{
      devices.forEach(device => {
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
//停止监听搜索到新设备的事件
  bleoffDeviceFoundBtn(){
    BLEAPI.bleoffDeviceFound()
  },
//创建蓝牙连接
  bleCreateConnectBtn(){
    var deviceId = this._deviceId
    BLEAPI.bleCreateConnect(deviceId).then(()=> {
       this.setData({
        hwStatusLabel : "蓝牙已连接"+deviceId
      })  
    })
  },
//关闭蓝牙连接
  bleCloseConnectBtn(){
    var deviceId = this._deviceId
    BLEAPI.bleCloseConnect(deviceId).then(()=> {
      this.setData({
        hwStatusLabel : "蓝牙断开"+deviceId
      }) 
   })
  },
//获取蓝牙service
  bleGetServicesBtn(){
    var deviceId = this._deviceId
   BLEAPI.bleGetServices(deviceId).then((res)=>{
        console.log(res.services[0].uuid+res.services[0].isPrimary)
        this.setData({
          hwStatusLabel : "获取到services"
        }) 
   })
  },
//获取蓝牙Characteristic
  bleGetCharacteristicBtn(){
    var deviceId = this._deviceId
    var seriveId = this._serviceID[0]
    BLEAPI.bleGetCharacteristic(deviceId,seriveId).then((res)=>{
      console.log(res.characteristics[0].uuid+res.characteristics[0].properties)
      this.setData({
        hwStatusLabel : "获取到characteristics"
      }) 
    })
  },
//读取Characteristic上的数据
  bleReadCharacteristicValueBtn(){
    var deviceId = this._deviceId
    var seriveId = this._serviceID[0]
    var characteristicId = this._characteristicId_read
    BLEAPI.bleReadCharacteristicValue(deviceId,seriveId,characteristicId).then((res)=>{
      console.log("read"+characteristicId+"sucess")
    })
  },
//向Characteristic写入数据
  bleWriteCharacteristicValueBtn(){
    var deviceId = this._deviceId
    var seriveId = this._serviceID[0]
    var characteristicId = this._characteristicId_write
    var lati = parseFloat(this._latitude).toFixed(5)
    var long = parseFloat(this._longitude).toFixed(5)
    var buffer = "OPENbluetooth00lati" + lati + "long" + long
    BLEAPI.bleWriteCharacteristicValue(deviceId,seriveId,characteristicId,buffer).then((res)=>{
      console.log("write"+buffer+"into"+characteristicId+"sucess")
      this.setData({
        hwStatusLabel : "写入命令成功"
      }) 
    })
  },
//使能Characteristic数据变化监听
  bleNotifyCharacteristicValueChangeBtn(){
    var deviceId = this._deviceId
    var seriveId = this._serviceID[0]
    //TODO 明确应该使能哪个特征值 并打印出来
    var characteristicId = this._characteristicId_at
    BLEAPI.bleNotifyCharacteristicValueChange(deviceId,seriveId,characteristicId).then((res)=>{
      console.log("enable"+characteristicId+" notify sucess")
      this.setData({
        hwStatusLabel : "使能Notify"
      }) 
    })
  },
//开启Characteristic数据变化监听
  bleOnCharacteristicValueChangeBtn(){
    BLEAPI.bleOnCharacteristicValueChange(function (res) {
      console.log("bleOnCharacteristicValueChange value: "+res.value)
      this.setData({
        hwStatusLabel : "监测到数据变化"+res.value
      }) 
    })

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onReady: function () {
    //初始化数据
     this._bleAble = false
     this._serviceID = [RFBMBG22A1_service_id]
     this._deviceId = ''
     this._characteristicId_read = RFBMBG22A1_characteristic_id_read
     this._characteristicId_write = RFBMBG22A1_characteristic_id_write
     this._characteristicId_at = RFBMBG22A1_characteristic_id_at
     this._latitude = "39.916927"
     this._longitude = "116.403119"    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

})
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}